//
//  Document.m
//  GCDTest
//
//  Created by 万伟琦 on 2018/9/28.
//  Copyright © 2018年 万伟琦. All rights reserved.
//

#import "Document.h"

@implementation Document

- (instancetype)init {
    if (self = [super init]) {
        _page = 0;
        _lock = [[NSConditionLock alloc] initWithCondition:4];
    }
    return self;
}



- (void)appendPage {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        
            self.page++;
            sleep(0.5);
        
        
    });
}


- (void)removePages {
    
    self.page = 0;
    
}

- (void)writePagesToDisk:(void(^)(void))completion {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"current page: %ld", self.page);
        sleep(0.5);
    });
}


- (void)run {

    for (int i = 0; i < 100; i++) {

        [self appendPage];

            @synchronized([Document class]){
                if (self.page > 3) {

                    [self writePagesToDisk:^{
                        [self removePages];
                    }];

                }
            }
    }
}



@end
